package com.heima.schedule.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.TaskDTO;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;


@Service
@Slf4j
@Transactional
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;


    /**
     * @param task 任务对象
     * @return
     */
    @Override
    public long addTask(TaskDTO task) {
        //1、保存任务到数据库
        boolean isSuccess = addTaskToDB(task);
        //2、保存任务到redis
        if (isSuccess) {
            addTaskToRedis(task);
        }

        return 0;
    }


    /**
     * 拉取任务
     *
     * @param taskType
     * @param priority
     * @return
     */
    @Override
    public TaskDTO popTask(Integer taskType, Integer priority) {
        //从redis中拉取数据
        String key = taskType + "_" + priority;
        TaskDTO task = null;
        try {
            //将任务从list中取出
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(task_json)) {
                task = JSON.parseObject(task_json, TaskDTO.class);
                //更新数据库信息
                updateDB(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("poll task exception");
        }
        return task;
    }


    /**
     * 添加符合条件的任务到redis缓存
     * 1.如果当前任务的执行时间<=当前系统时间:将任务添加到list中
     * 2.预设时间(当前时间+5min) >=当前任务的执行时间>当前的系统时间:
     * 将任务添加到ZSet中
     *
     * @param task
     */
    private void addTaskToRedis(TaskDTO task) {
        String key = task.getTaskType() + "_" + task.getPriority();

        //获取五分钟后的时间（毫秒值）
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long nextScheduleTime = calendar.getTimeInMillis();

        //2.1 如果执行任务时间小于当前时间，则将任务保存到list中
        if (task.getExecuteTime() < System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() < nextScheduleTime) {
            //2.2 如果执行任务时间大于当前时间 && 小于预设时间，则保存到zSet中
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }

    }

    /**
     * 添加任务到数据库
     *
     * @param task
     * @return
     */
    private boolean addTaskToDB(TaskDTO task) {
        boolean flag = false;
        try {
            //将任务信息保存到任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置taskId
            task.setTaskId(taskinfo.getTaskId());

            //将任务信息保存到任务日志表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);

            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * redis定时刷新
     * 每分钟刷新异常:将zset中符合条件的数据刷到list中
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refreshRedis() {
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (StringUtils.isNotBlank(token)) {

            log.info("未来数据定时刷新---定时任务");
            //获取未来数据集合的key值
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");//future_*
            for (String futureKey : futureKeys) { //futureKey future_100_200
                //获取当前数据的key topic
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                //查询已经到期的任务
                Set<String> tasks = cacheService.zRange(futureKey, 0, System.currentTimeMillis());
                //将任务同步到list中
                if (!tasks.isEmpty()) {
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                }
            }
        }
    }



    /**
     * 删除任务，更新任务日志
     *
     * @param taskId
     * @return
     */
    private TaskDTO updateDB(long taskId, int status) {
        TaskDTO task = null;
        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);
            //删除任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            //返回任务内容
            task = new TaskDTO();
            BeanUtils.copyProperties(taskinfoLogs, task);
            //纪录执行时间，以此来判断在redis的list还是zset中删除
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());

        } catch (Exception e) {
            log.error("task cancel exception taskid={}", taskId);
        }
        return task;


    }

    /**
     * DB中的任务定时刷新到redis
     * 每五分钟刷新一次
     */
    @PostConstruct
    @Scheduled(cron = "0 */5 * * * ?")
    public void refreshDBToRedis() {
        clearCache();
        log.info("数据库同步到缓存");

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, 5);

        //查看小于未来五分钟的所有任务（设置预设时间的目的是为了防止大量数据进入缓存）
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, instance.getTime()));
        if (taskinfoList != null && taskinfoList.size() > 0) {
            for (Taskinfo taskinfo : taskinfoList) {
                TaskDTO task = new TaskDTO();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToRedis(task);
            }
        }
    }


    /**
     * 将缓存中的数据清除，防止任务重复
     */
    public void clearCache(){
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);
    }
}